package com.a1573595.musicplayer.show_Lyrics

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.a1573595.musicplayer.PlayerApplication
import com.a1573595.musicplayer.databinding.ActivityLyricsBinding

class LyricsActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLyricsBinding
    private lateinit var layoutManager: LinearLayoutManager
    private lateinit var lyricsAdapter: LyricsAdapter
    private val handler = Handler(Looper.getMainLooper())
    private lateinit var updateLyricsRunnable: Runnable

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLyricsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val playerService = (application as PlayerApplication).playerService
        val playSongActivity=(application as PlayerApplication).playSongActivity

        val lyrics: List<Pair<Int, String>> = playerService?.parsedLyrics ?: emptyList()
        var currentTime = playSongActivity?.currentLyricPosition?:0


        layoutManager = LinearLayoutManager(this)
        lyricsAdapter = LyricsAdapter(lyrics, currentTime)
        binding.recyclerViewLyrics.apply {
            layoutManager = this@LyricsActivity.layoutManager
            adapter = lyricsAdapter
        }
        // 滚动到当前歌词位置并将其居中
        scrollToCurrentLyric(currentTime)

        // 初始化并启动定时任务
        initUpdateLyricsRunnable()
        handler.post(updateLyricsRunnable)
    }
    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(updateLyricsRunnable)
    }
    private fun scrollToCurrentLyric(position: Int) {
        binding.recyclerViewLyrics.post {
            val offset = binding.recyclerViewLyrics.height / 2 // RecyclerView 高度的一半
            layoutManager.scrollToPositionWithOffset(position, offset)
        }
    }
    private fun initUpdateLyricsRunnable() {
        updateLyricsRunnable = Runnable {
            val playSongActivity = (application as PlayerApplication).playSongActivity
            val currentTime = playSongActivity?.currentLyricPosition ?: 0
            lyricsAdapter.setCurrentLyricPosition(currentTime)
            scrollToCurrentLyric(currentTime)
            handler.postDelayed(updateLyricsRunnable, 1000) // 每秒更新一次
        }
    }

}